// Package objective 实现客观周期同步系统
// 基于四维一体法则的第四维度：客观周期
package objective

import (
	"fmt"
	"time"
)

// TimeRange 时间范围
type TimeRange struct {
	Start time.Time
	End   time.Time
}

// Task 量子任务
type Task struct {
	ID          string
	Name        string
	Activity    string
	Priority    int
	Duration    time.Duration
	ScheduledAt time.Time
	Completed   bool
}

// RhythmSynchronizer 节律同步器
type RhythmSynchronizer struct {
	EarthResonance float64 // 地球舒曼共振频率 7.83 Hz
	WorkCycles     map[string]TimeRange
	CurrentCycle   string
	Tasks          []*Task
	SyncEnabled    bool
}

// WorkCycle 工作周期定义
var DefaultWorkCycles = map[string]string{
	"深度编码":  "02:00-06:00", // 量子思维高峰期
	"算法设计":  "09:00-11:00", // 逻辑构建期
	"测试验证":  "15:00-17:00", // 客观检验窗口
	"量子休息":  "22:00-02:00", // 系统重组时间
	"集成开发":  "10:00-12:00", // 系统集成期
	"文档撰写":  "14:00-16:00", // 知识固化期
	"代码审查":  "16:00-18:00", // 质量保障期
	"创新思考":  "20:00-22:00", // 灵感涌现期
}

// NewRhythmSynchronizer 创建新的节律同步器
func NewRhythmSynchronizer() *RhythmSynchronizer {
	rs := &RhythmSynchronizer{
		EarthResonance: 7.83,
		WorkCycles:     make(map[string]TimeRange),
		Tasks:          make([]*Task, 0),
		SyncEnabled:    true,
	}

	// 初始化工作周期
	rs.initializeWorkCycles()

	return rs
}

// initializeWorkCycles 初始化工作周期
func (rs *RhythmSynchronizer) initializeWorkCycles() {
	now := time.Now()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())

	for activity, timeRange := range DefaultWorkCycles {
		startTime, endTime := rs.parseTimeRange(timeRange)
		
		start := today.Add(time.Duration(startTime.Hour())*time.Hour + time.Duration(startTime.Minute())*time.Minute)
		end := today.Add(time.Duration(endTime.Hour())*time.Hour + time.Duration(endTime.Minute())*time.Minute)

		// 如果结束时间小于开始时间，说明跨越了午夜
		if end.Before(start) {
			end = end.Add(24 * time.Hour)
		}

		rs.WorkCycles[activity] = TimeRange{
			Start: start,
			End:   end,
		}
	}
}

// SyncWithEarthResonance 与地球共振同步
func (rs *RhythmSynchronizer) SyncWithEarthResonance() error {
	if !rs.SyncEnabled {
		return fmt.Errorf("节律同步未启用")
	}

	// 计算当前时间与地球共振的相位
	now := time.Now()
	// 地球舒曼共振周期约为 0.128 秒 (1/7.83 Hz)
	resonancePeriod := time.Duration(1000.0/rs.EarthResonance) * time.Millisecond

	// 计算相位偏移
	phase := float64(now.UnixNano()%int64(resonancePeriod)) / float64(resonancePeriod)

	// 如果相位接近0.5（最不利时机），建议等待
	if phase > 0.4 && phase < 0.6 {
		return fmt.Errorf("当前相位不利于量子操作，建议等待 %.2f 秒", 
			float64(resonancePeriod)*(0.6-phase)/float64(time.Second))
	}

	return nil
}

// GetOptimalWorkTime 获取最佳工作时间
func (rs *RhythmSynchronizer) GetOptimalWorkTime(activity string) (time.Time, error) {
	timeRange, exists := rs.WorkCycles[activity]
	if !exists {
		return time.Time{}, fmt.Errorf("未知的活动类型: %s", activity)
	}

	now := time.Now()

	// 如果当前时间在最佳时间范围内
	if now.After(timeRange.Start) && now.Before(timeRange.End) {
		return now, nil
	}

	// 如果当前时间在范围之前
	if now.Before(timeRange.Start) {
		return timeRange.Start, nil
	}

	// 如果当前时间在范围之后，返回明天的开始时间
	return timeRange.Start.Add(24 * time.Hour), nil
}

// CheckRhythmAlignment 检查节律对齐状态
func (rs *RhythmSynchronizer) CheckRhythmAlignment() bool {
	now := time.Now()
	
	// 检查是否在任何一个工作周期内
	for _, timeRange := range rs.WorkCycles {
		if now.After(timeRange.Start) && now.Before(timeRange.End) {
			return true
		}
	}

	return false
}

// GetCurrentCycle 获取当前工作周期
func (rs *RhythmSynchronizer) GetCurrentCycle() string {
	now := time.Now()

	for activity, timeRange := range rs.WorkCycles {
		if now.After(timeRange.Start) && now.Before(timeRange.End) {
			rs.CurrentCycle = activity
			return activity
		}
	}

	return "休息期"
}

// ScheduleQuantumTask 调度量子任务
func (rs *RhythmSynchronizer) ScheduleQuantumTask(task *Task) error {
	if task == nil {
		return fmt.Errorf("任务不能为空")
	}

	// 根据活动类型找到最佳时间
	optimalTime, err := rs.GetOptimalWorkTime(task.Activity)
	if err != nil {
		return fmt.Errorf("调度任务失败: %w", err)
	}

	task.ScheduledAt = optimalTime
	rs.Tasks = append(rs.Tasks, task)

	return nil
}

// GetScheduledTasks 获取已调度的任务
func (rs *RhythmSynchronizer) GetScheduledTasks() []*Task {
	return rs.Tasks
}

// GetPendingTasks 获取待处理任务
func (rs *RhythmSynchronizer) GetPendingTasks() []*Task {
	pending := make([]*Task, 0)
	for _, task := range rs.Tasks {
		if !task.Completed {
			pending = append(pending, task)
		}
	}
	return pending
}

// CompleteTask 完成任务
func (rs *RhythmSynchronizer) CompleteTask(taskID string) error {
	for _, task := range rs.Tasks {
		if task.ID == taskID {
			task.Completed = true
			return nil
		}
	}
	return fmt.Errorf("任务未找到: %s", taskID)
}

// GetRhythmReport 获取节律报告
func (rs *RhythmSynchronizer) GetRhythmReport() map[string]interface{} {
	now := time.Now()
	currentCycle := rs.GetCurrentCycle()
	aligned := rs.CheckRhythmAlignment()

	// 计算下一个最佳工作周期
	nextCycle := rs.getNextCycle()

	// 统计任务
	totalTasks := len(rs.Tasks)
	completedTasks := 0
	for _, task := range rs.Tasks {
		if task.Completed {
			completedTasks++
		}
	}

	return map[string]interface{}{
		"current_time":      now.Format("15:04:05"),
		"current_cycle":     currentCycle,
		"rhythm_aligned":    aligned,
		"next_cycle":        nextCycle,
		"earth_resonance":   rs.EarthResonance,
		"sync_enabled":      rs.SyncEnabled,
		"total_tasks":       totalTasks,
		"completed_tasks":   completedTasks,
		"pending_tasks":     totalTasks - completedTasks,
		"work_cycles":       len(rs.WorkCycles),
	}
}

// GetWorkCycleSchedule 获取工作周期时间表
func (rs *RhythmSynchronizer) GetWorkCycleSchedule() map[string]string {
	schedule := make(map[string]string)
	for activity, timeRange := range rs.WorkCycles {
		schedule[activity] = fmt.Sprintf("%s - %s",
			timeRange.Start.Format("15:04"),
			timeRange.End.Format("15:04"))
	}
	return schedule
}

// IsOptimalTime 判断是否为最佳时间
func (rs *RhythmSynchronizer) IsOptimalTime(activity string) bool {
	timeRange, exists := rs.WorkCycles[activity]
	if !exists {
		return false
	}

	now := time.Now()
	return now.After(timeRange.Start) && now.Before(timeRange.End)
}

// WaitForOptimalTime 等待最佳时间
func (rs *RhythmSynchronizer) WaitForOptimalTime(activity string) error {
	optimalTime, err := rs.GetOptimalWorkTime(activity)
	if err != nil {
		return err
	}

	now := time.Now()
	if now.Before(optimalTime) {
		waitDuration := optimalTime.Sub(now)
		if waitDuration > 0 {
			time.Sleep(waitDuration)
		}
	}

	return nil
}

// 辅助方法

func (rs *RhythmSynchronizer) parseTimeRange(timeRange string) (start, end time.Time) {
	// 解析 "HH:MM-HH:MM" 格式
	var startHour, startMin, endHour, endMin int
	fmt.Sscanf(timeRange, "%d:%d-%d:%d", &startHour, &startMin, &endHour, &endMin)

	now := time.Now()
	start = time.Date(now.Year(), now.Month(), now.Day(), startHour, startMin, 0, 0, now.Location())
	end = time.Date(now.Year(), now.Month(), now.Day(), endHour, endMin, 0, 0, now.Location())

	return start, end
}

func (rs *RhythmSynchronizer) getNextCycle() string {
	now := time.Now()
	var nextCycle string
	var minDuration time.Duration = 24 * time.Hour

	for activity, timeRange := range rs.WorkCycles {
		if timeRange.Start.After(now) {
			duration := timeRange.Start.Sub(now)
			if duration < minDuration {
				minDuration = duration
				nextCycle = activity
			}
		}
	}

	if nextCycle == "" {
		// 所有周期都已过，找明天的第一个
		for activity, timeRange := range rs.WorkCycles {
			nextStart := timeRange.Start.Add(24 * time.Hour)
			duration := nextStart.Sub(now)
			if duration < minDuration {
				minDuration = duration
				nextCycle = activity
			}
		}
	}

	return nextCycle
}
